package com.hmdp.utils;

import com.hmdp.dto.UserDTO;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 24040
 * @name LoginInterceptor
 * @date 2022-09-02 17:20
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取session
        HttpSession session = request.getSession();

        // 获取session中的用户
        Object user = session.getAttribute("user");
        // 判断用户是否存在
        if (user==null) {
            //不存在拦截,并返回401状态码，未授权
            response.setStatus(401);
            return false;
        }

        //存在则放行，并保存到threadLocal中
        UserHolder.saveUser((UserDTO) user);
        return true;
    }
}
